package bmatch.tech.todo.service.impl;

import bmatch.tech.todo.dao.TodoUserMapper;
import bmatch.tech.todo.model.LoginUser;
import bmatch.tech.todo.model.User;
import bmatch.tech.todo.service.EmailService;
import bmatch.tech.todo.service.UserService;
import bmatch.tech.todo.util.IDUtils;
import bmatch.tech.todo.util.PwdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @program:todo
 * @author:LinJinhao
 * @create:2018-12-31 14:51
 **/
@Service
public class UserServiceImpl implements UserService {

    private final TodoUserMapper userMapper;

    private final EmailService emailService;

    //利用Map缓存邮件传来的激活码
    private Map<String, String> cdKeyMap = new HashMap<>();

    @Autowired
    public UserServiceImpl(EmailService emailService,TodoUserMapper userMapper){
        this.userMapper = userMapper;
        this.emailService = emailService;
    }

    //检查邮箱是否已注册
    @Override
    public boolean checkMailReg(String emailAddress) {
        if (userMapper.selectByEmail(emailAddress)!=null){
            return false;
        }else {
            return true;
        }
    }

    //生成激活码
    @Override
    public String createCdKey(String email) {
        String cdKey = IDUtils.get6UUID().toUpperCase();
        //将验证码保存到Map，自定义定时器设置5分钟失效
        cdKeyMap.put(email,cdKey);
        emailService.send(email,"尊敬的TODO用户","您好！\n您本次的TODO验证码为：\n"+cdKey+"\n请在五分钟内输入，否则失效。");

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                cdKeyMap.clear();
            }
        },5 * 60 * 1000);

        return cdKey;
    }

    //验证激活码
    @Override
    public boolean verifyCdKey(String email ,String text) {
        String cdKeyFromEmail = cdKeyMap.get(email);

        if (cdKeyFromEmail == null ||
            !cdKeyFromEmail.equals(text)){
            return false;
        }
        return true;
    }

    //注册成功导入数据库
    @Override
    public LoginUser register(User user) {
        User newUser = initUser(user);
        userMapper.insert(newUser);
        return userMapper.selectByPrimaryKey(newUser.getId());
    }

    //根据邮箱和密码到数据匹配
    @Override
    public LoginUser login(String email, String pwd) {
        LoginUser loginUser = userMapper.selectByEmailAndPwd(email,pwd);
        return loginUser;
    }

    //根据用户邮箱发送的验证码找回密码
    @Override
    public boolean foundPwd(String userId, String pwd) {
        LoginUser user = new User();
        String MD5Pwd = PwdUtils.md5Password(pwd, "bmatch");
        int pwdLength = pwd.length();
        int r = userMapper.updateByPrimaryKey(userId,MD5Pwd,pwdLength);
        if (r < 0) {
            return false;
        }else {
            user.setGmtCreated(new Date());
            user.setGmtModified(new Date());
            return true;
        }
    }

    //通过邮箱查询用户信息
    @Override
    public LoginUser getUserByEmail(String email) {
        LoginUser loginUser = userMapper.selectByEmail(email);
        return loginUser;
    }

    //更新用户信息
    @Override
    public boolean updateUser(LoginUser user) {
        user.setGmtCreated(new Date());
        if (userMapper.updateDateByUserId(user) < 0){
            return false;
        }else {
            return true;
        }
    }

    //通过用户主键取得用户信息
    @Override
    public LoginUser getUserById(String id) {
        LoginUser loginUser = userMapper.selectByPrimaryKey(id);
        return loginUser;
    }

    //将新用户数据导入数据库中
    @Override
    public User initUser(User user) {
        User newUser = new User();
        newUser.setId(IDUtils.get10UUID());
        newUser.setGmtCreated(new Date());
        newUser.setGmtModified(new Date());
        newUser.setEmail(user.getEmail());
        newUser.setNickName("New user"+IDUtils.get4UUID());

        String pwd = PwdUtils.md5Password(user.getPwd(),"bmatch");
        newUser.setPwd(pwd);
        newUser.setSlat("bmatch");
        newUser.setEncrypt("md5");
        newUser.setPwdLength(pwd.length());

        return newUser;
    }
}
